package options

import (
	"gitee.com/youkelike/ziam/zapi/scheme"
	"gitee.com/youkelike/ziam/zsdk2/gosdk/service/ziam"
	"gitee.com/youkelike/ziam/zsdk2/rest"
	"gitee.com/youkelike/ziam/zutils/runtime"
)

// 同时拥有获取 zsdk2 配置对象和客户端对象的能力
type Factory interface {
	RESTClientGetter

	ZiamClient() (*ziam.ZiamClient, error)
	RESTClient() (*rest.RESTClient, error)
}

type factoryImpl struct {
	clientGetter RESTClientGetter
}

func NewFactory(clientGetter RESTClientGetter) Factory {
	if clientGetter == nil {
		panic("attempt to instantiate client_access_factory with nil clientGetter")
	}

	f := &factoryImpl{
		clientGetter: clientGetter,
	}

	return f
}

func (f *factoryImpl) ToRESTConfig() (*rest.Config, error) {
	return f.clientGetter.ToRESTConfig()
}

// 获取 zsdk2 的 ziam 应用层客户端
func (f *factoryImpl) ZiamClient() (*ziam.ZiamClient, error) {
	clientConfig, err := f.ToRESTConfig()
	if err != nil {
		return nil, err
	}
	return ziam.NewForConfig(clientConfig)
}

// 获取 zsdk2 最底层的 REST 客户端
func (f *factoryImpl) RESTClient() (*rest.RESTClient, error) {
	clientConfig, err := f.ToRESTConfig()
	if err != nil {
		return nil, err
	}
	SetIAMDefaults(clientConfig)
	return rest.RESTClientFor(clientConfig)
}

func SetIAMDefaults(config *rest.Config) error {
	config.GroupVersion = &scheme.GroupVersion{Group: "apiserver", Version: "v1"}

	if config.APIPath == "" {
		config.APIPath = "/api"
	}
	if config.Negotiator == nil {
		// 底层实现了一个 json 编解码器
		config.Negotiator = runtime.NewSimpleClientNegotiator()
	}
	return rest.SetIAMDefaults(config)
}
